package com.ukao.pad.ui.orders;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.ukao.pad.R;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.VipGroupBean;
import com.ukao.pad.bean.VipLeverBean;
import com.ukao.pad.consts.GlobalConsts;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.ChooseDialogFragment;
import com.ukao.pad.dialog.DialogTool;
import com.ukao.pad.eventbus.ChooseCardEvent;
import com.ukao.pad.presenter.CreateVipPresenter;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.RegularUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.CreateVipView;
import com.ukao.pad.widget.ClearEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.pad.utils.MyDateUtils.getTime;

/**
 *  新建会员
 */
public class CreateVipFragment extends MvpFragment<CreateVipPresenter> implements CreateVipView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Unbinder unbinder;
    private OnFragmentInteractionListener mListener;
    @BindView(R.id.key_recycler_view)
    RecyclerView keyRecyclerView;
    @BindView(R.id.btn_save_information)
    Button printOrder;
    @BindView(R.id.txt_phone)
    ClearEditText phoneInput;
    @BindView(R.id.clean_button)
    Button cleanButton;
    @BindView(R.id.txt_name)
    ClearEditText nameInput;
    @BindView(R.id.man)
    RadioButton rbMan;
    @BindView(R.id.girl)
    RadioButton rbGirl;
    @BindView(R.id.vip_card)
    Button vipCard;
    @BindView(R.id.btn_birthday)
    Button birthdayBtn;    //出生日期按钮
    @BindView(R.id.grouping)
    Button grouping;
    @BindView(R.id.back)
    TextView back;
    private String timeType = "yyyy-MM-dd";
    private String phone;
    private ArrayList<VipLeverBean.ListBean> vipLeverData;
    private ArrayList<VipGroupBean> mvipGroupDatas;
    private ArrayList<VipGroupBean> vipGroupingData;
    private ArrayList<VipLeverBean.ListBean> mvipleverData;
    private VipLeverBean.ListBean listBean;
    private VipGroupBean vipGroupBean;
    private String strPhone;
    private String strName;
    private String birthday;
    private String cardId = "";
    private String groupId = "";
    private String sex;
    private  String storeId;
    public CreateVipFragment() {
    }

    public static CreateVipFragment newInstance(String param1, String param2,String str) {
        CreateVipFragment fragment = new CreateVipFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        args.putSerializable(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    public static CreateVipFragment newInstance(String phone,String storeId) {
        CreateVipFragment fragment = new CreateVipFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM3, phone);
        args.putString(ARG_PARAM4, storeId);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            phone=getArguments().getString(ARG_PARAM3);
            storeId =getArguments().getString(ARG_PARAM4);
            vipGroupingData = new ArrayList<VipGroupBean>();
            mvipleverData = new ArrayList<VipLeverBean.ListBean>();
            vipLeverData=new ArrayList<VipLeverBean.ListBean>();
//            if (null == phone) {
//                mvipGroupDatas = (ArrayList<VipGroupBean>) getArguments().getSerializable(ARG_PARAM1);
//                if (!CheckUtils.isEmpty(mvipGroupDatas)) {
//                    vipGroupingData.addAll(mvipGroupDatas);
//                    vipGroupingData.remove(0);
//                }
//                mvipleverData = (ArrayList<VipLeverBean.ListBean>) getArguments().getSerializable(ARG_PARAM2);
//                if (!CheckUtils.isEmpty(vipLeverData)) {
//                    mvipleverData.addAll(vipLeverData);
//                    mvipleverData.remove(0);
//                }
//
//            }
        }
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }
    @Override
    protected void initView() {
        if (phone != null) {
            phoneInput.setText(phone);
            //请求会员卡等级
            mvpPresenter.requestVipCardLever(getActivity());
        }
        if (!CheckUtils.isNull(vipGroupingData)) {
            for (VipGroupBean vipGroupBean : vipGroupingData) {
                vipGroupBean.setCheck(false);
            }
        }
        birthdayBtn.setText("请选择");
        setDefaultChecked();
        phoneInput.requestFocus();
        KeyBoardUtil.showKeyboard(phoneInput);
//        time.setText(R.string.please_select);
//        // time.setText(MyDateUtils.formatDate(MyDateUtils.getDateYearsago()));
//        String[] keyBoardData = getResources().getStringArray(R.array.vip_keyboard);
//        initGridRecyclerView(keyRecyclerView, 3);
//        mKeyboardAdapter = new KeyboardAdapter(activity, Arrays.asList(keyBoardData));
//        mKeyboardAdapter.setIsVipEnter(true);
//        keyRecyclerView.setAdapter(mKeyboardAdapter);

    }

    /**
     * 设置默认选中的 分组和
     */
    private void setDefaultChecked() {
        if (!CheckUtils.isEmpty(vipLeverData) && !CheckUtils.isEmpty(vipGroupingData)) {
            for (VipLeverBean.ListBean listBean : vipLeverData) {
                if (listBean.getDef()) {
                    vipCard.setText(listBean.getName());
                    cardId = listBean.getId();
                    listBean.setCheck(true);
                } else {
                    listBean.setCheck(false);
                }
            }
            VipGroupBean vipGroupBean = vipGroupingData.get(0);
            groupId = vipGroupBean.getId();
            grouping.setText(vipGroupBean.getName());
            vipGroupBean.setCheck(true);
        }
    }
    @OnClick({R.id.btn_save_information,R.id.btn_birthday,R.id.vip_card,R.id.grouping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_save_information:  //保存按钮
                strPhone = getText(phoneInput);
                strName = getText(nameInput);
                birthday = getText(birthdayBtn);
                String strVipCard = getText(vipCard);
                if (!RegularUtils.isMobileSimple(strPhone)) {
                    T.show("请输入正确手机号");
                    return;
                } else if (strName.isEmpty()) {
                    T.show("请输入名字");
                    return;
                } else if (strVipCard.isEmpty()) {
                    T.show("请选择会员卡");
                    return;
                } else if (!rbMan.isChecked() && !rbGirl.isChecked()) {
                    T.show("请输入选择性别");
                    return;
                }
                if (rbMan.isChecked()) {
                    sex = "1";
                } else {
                    sex = "2";
                }
                saveVipInfo();
                break;
            case R.id.btn_birthday:   //请选择
                String birthday = birthdayBtn.getText().toString();
                birthday = birthday.equals("请选择") ? "" : birthday;
                DialogTool.getSingleton().showDatePicker(birthday, timeType, getActivity(), mOnTimeSelectListener);
                break;
            case R.id.vip_card:  //会员卡选择
                ChooseDialogFragment vipDialog = new ChooseDialogFragment();
                Bundle vipBundle = new Bundle();
                vipBundle.putString("Type", GlobalConsts.VIP_LEVER_ENTER);
                vipBundle.putParcelableArrayList("dataList", vipLeverData);
                vipDialog.setArguments(vipBundle);
                vipDialog.show(getChildFragmentManager(), GlobalConsts.VIP_LEVER_ENTER);
                break;
            case R.id.grouping:  //分组
                ChooseDialogFragment chooseTime = new ChooseDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("Type", GlobalConsts.VIP_GROUND_ENTER);
                bundle.putParcelableArrayList("dataList",vipGroupingData);
                chooseTime.setArguments(bundle);
                chooseTime.show(getChildFragmentManager(),GlobalConsts.VIP_GROUND_ENTER);
                break;
        }
    }
    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            birthdayBtn.setText(getTime(date, timeType));
        }
    };

    /**
     * 保存vip信息
     */
    private void saveVipInfo() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
        mHashMap.put("name", strName);
        mHashMap.put("phone",strPhone);
        mHashMap.put("sex", sex);
        mHashMap.put("cardId", cardId + "");
        mHashMap.put("birthday", birthday.equals("请选择")? "" : birthday);
        mHashMap.put("groupId", groupId);
        mHashMap.put("storeId",storeId);
        mvpPresenter.saveVipInfo(mHashMap);
        L.i("mHashMap=" + mHashMap.toString());
    }

    @Override
    protected CreateVipPresenter createPresenter() {
        return new CreateVipPresenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_create_vip, container, false);
        unbinder=ButterKnife.bind(this,view);
        return view;
    }

    /**
     * 选择卡事件
     * @param event
     */
    @Subscribe()
    public void onEvent(ChooseCardEvent event) {
        switch (event.getMessage()) {
            case groud:
                vipGroupBean = (VipGroupBean) event.getData();
                if(vipGroupBean!=null){
                    grouping.setText(vipGroupBean.getName());
                    groupId = vipGroupBean.getId();
                }
                break;
            case lever:
                listBean = (VipLeverBean.ListBean) event.getData();
                if(listBean!=null){
                    vipCard.setText(listBean.getName());
                    cardId = listBean.getId();
                }
                break;
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }
    @Override
    public void onDetach() {
        super.onDetach();
    }
    @Override
    public void loadFailure(String message) {
        T.show(message);
    }

    /**
     * 加载会员卡等级成功
     * @param vipLeverBean
     */
    @Override
    public void loadVipCardLeverSucceed(List<VipLeverBean.ListBean> vipLeverBean) {
        vipLeverData.addAll(vipLeverBean);
    }
    @Override
    public void buildUserSucceed() {
        Bundle bundle = new Bundle();
        if (phone == null) {
            bundle.putString("phone", "");
            bundle.putString("groupId", groupId);
        } else {
            bundle.putString("phone", strPhone);
        }
        setFragmentResult(RESULT_OK, bundle);
        finish();
    }

    /**
     *  加载全部分组成功
     * @param list
     */
    @Override
    public void loadAllGroupSucceed(List<VipGroupBean> list) {
        vipGroupingData.addAll(list);
        setDefaultChecked();
    }

    @Override
    public void loadvipGroupSucceed(List<VipGroupBean> listGroup) {
        vipGroupingData.addAll(listGroup);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
